/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-25 14:17:31
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-04-24 15:43:55
 */
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from './user'

const Err404 = () => import('@/views/system/Error/404.vue')

const asyncRouterHandle = (asyncRouter) => {
	const modules = import.meta.glob('../views/**/*.vue')
	let routes = [] as Array<RouteRecordRaw>
	routes = asyncRouter
		.map((item) => {
			if (item.path) {
				// 如果配置了参数，先把参数截出做查理
				let querys = []
				if (item.path && item.path.includes('?')) {
					querys = item.path.split('?')
				} else {
					querys = [item.path]
				}
				let prefix = ''
				let tempPath = querys[0].includes('index') ? querys[0] + '.vue' : querys[0] + '/index.vue'
				if (tempPath.includes('~')) {
					tempPath = tempPath.split('~')[1]
					prefix = item.path.split('~')[0].replace('/', '')
				}
				let component = modules['../views' + tempPath]
				if (component) {
					let route = {
						path: querys[0],
						query: querys[1] ? querys[1] : null,
						name: item.path.replace('/', '_'),
						meta: {
							icon: item.icon,
							parentId: item.parentId || '/',
							menuId: item.id || '/',
							title: item.name,
							transition: '',
							prefix,
						},
						component: component,
					}
					return route
				}
			}
		})
		.filter(Boolean)
	return routes
}

export const useRouterStore = defineStore('router', () => {
	const asyncRouters = ref([])
	const SetAsyncRouter = async () => {
		const userStore = useUserStore()
		const web_menu = await userStore.GetUserInfo()
		asyncRouters.value = web_menu ? asyncRouterHandle(web_menu) : []
	}
	const LoadRecRoute = (router) => {
		return new Promise(async (resolve, reject) => {
			await SetAsyncRouter()
			router.removeRoute('NoFound')
			asyncRouters.value.forEach((asyncRouter) => {
				router.addRoute('Home', asyncRouter)
			})
			router.addRoute({
				path: '/:all(.*)*',
				name: 'NoFound',
				meta: {
					purl: '',
					transition: 'slide-left',
					title: '404',
				},
				component: Err404,
			})
			resolve(asyncRouters.value)
		})
	}
	return {
		asyncRouters,
		LoadRecRoute,
	}
})
